﻿using HHG.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace OnLineExam.Web.handler
{
	/// <summary>
	/// exam 的摘要说明
	/// </summary>
	public class exam :BasePage, IHttpHandler,IRequiresSessionState
	{
		private HttpContext _httpContext;
		private HttpRequest _httpRequest;
		private HttpResponse _httpResponse;

        

        private readonly OnLineExam.Data.EfRepository<Data.Score> _scoreRepository;
        private readonly OnLineExam.Data.EfRepository<OnLineExam.Data.Paper> _paperRepository;


        public exam() {
			_scoreRepository = new Data.EfRepository<Data.Score>(_ctx);
            _paperRepository = new Data.EfRepository<Data.Paper>(_ctx);

        }

		public override void ProcessRequest(HttpContext context)
		{
			_httpContext = context;
			_httpRequest = context.Request;
			_httpResponse = context.Response;

			context.Response.ContentType = "text/plain";

			var type = context.Request.Params["type"];

			switch (type)
			{
				case "getlist":
					GetList();
					break;
                case "startExam":
                    StartExam();
                    break;
                default:
					break;
			}
		}

        private void StartExam() {
            var userId = _httpRequest.Params["uid"];
            
            var paperId = _httpRequest.Params["pid"].GetInt();
            if (paperId <= 0)
            {
                WriteJson(Extensions.ResultCode.SetFail("paperId 异常"));
                return ;
            }
           _httpContext. Session["PaperID"] = paperId;
            _httpContext.Session["PaperName"] = _paperRepository.GetById(paperId).PaperName;

            if (_httpRequest.UserAgent.ToLower().Contains("linux"))
            {
                //Response.Redirect("mobile/test.aspx?id=" + PaperID);
            }
            var paper = _paperRepository.GetById(paperId);

            int allwortextcount = paper.allowExamNum;//允许考试次数


            var checkInfo = Extensions.PaperExtension.CheckIsAllowExam(userId, paperId);
            WriteJson(checkInfo);
        }

        private void GetList( ) {
			int page = _httpRequest.Params["page"].GetInt();
			int rows = _httpRequest.Params["rows"].GetInt();
			var userId = _httpRequest.Params["userId"];
			var query = _scoreRepository.TableNoTracking.Where(s=>s.UserID==userId);

			var result = EasyuiDataGrid.Create(query.Count(), query.OrderByDescending(s => s.ID).Skip((page - 1) * rows).Take(rows).Select(s=>new {  s.ID, paper =s.Paper.PaperName, examTime=s.ExamTime, score =s.UserScore, status = s.UserScore>s.Paper.passMark}).ToList());

			WriteJson(result);
		}
		private void WriteJson(object data)
		{
			_httpResponse.Write(data.SerializeObject());
			_httpResponse.End();
		}

		private void Check() {


		}

		public bool IsReusable
		{
			get
			{
				return false;
			}
		}
	}
}